package com.ruoyi.management.service.impl;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.management.base.utils.DateUtils;
import com.ruoyi.management.dao.mapper.BillingMapper;
import com.ruoyi.management.dao.mapper.WxMapper;
import com.ruoyi.management.pojo.entity.*;
import com.ruoyi.management.pojo.param.WXLogin;
import com.ruoyi.management.pojo.po.AmmeterResultPo;
import com.ruoyi.management.pojo.po.MouthReadPO;
import com.ruoyi.management.pojo.po.QldbqyinfoPO;
import com.ruoyi.management.pojo.po.QldbzymxPO;
import com.ruoyi.management.pojo.vo.*;
import com.ruoyi.management.service.AmmeterService;
import com.ruoyi.management.service.WxService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.YearMonth;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;


@Slf4j
@Service
public class WxImpl implements WxService {
    @Autowired
    private WxMapper wxMapper;
    @Autowired
    private BillingMapper billingMapper;
    @Autowired
    private AmmeterService ammeterService;

    @Override
    //改密码
    public Boolean changePassword(WXLogin wxLogin) {
        WXloginVO wXloginVO = wxMapper.selectUserByID(wxLogin.getYhID());
        if (wXloginVO.getPassword().equals(wxLogin.getPassword())) {
            Boolean a = wxMapper.updatepassword(wxLogin);
            return a;
        }
        return false;
    }

    //租户关联电表
    @Override
    public List<BillingVO> selectusergl(String khbh) {
        List<KhbhDbbh> khbhList = wxMapper.selectQldbzymx1(khbh);
        List<BillingVO> allResults = new ArrayList<>();

        for (KhbhDbbh kd : khbhList) {
            List<BillingVO> result = Ccompute(kd);
            allResults.addAll(result);
        }
        return allResults;
    }

    @Override
    public TenantHomeVO selectTenantHome(String khbh) {
        BigDecimal monthPower = BigDecimal.ZERO;
        BigDecimal totalPower = BigDecimal.ZERO;
        TenantHomeVO tenantHomeVO = new TenantHomeVO();
        tenantHomeVO.setAmmeterNum(wxMapper.selectAmmeterNum(khbh));
        tenantHomeVO.setFjhNum(wxMapper.selectRoomNum(khbh));
        List<BillingVO> allResults = selectusergl(khbh);
        for (BillingVO vo : allResults) {
            // 累加 e
            if (vo.getZzdl() != null) {
                monthPower = monthPower.add(vo.getE());
            }

            // 计算 b * magnification 并累加
            if (vo.getB() != null && vo.getMagnification() != null) {
                BigDecimal product = vo.getB().multiply(vo.getMagnification());
                totalPower = totalPower.add(product);
            }
        }
        tenantHomeVO.setMonthPower(monthPower);
        tenantHomeVO.setTotalPower(totalPower);
        return tenantHomeVO;
    }

    @Override
    public BigDecimal monthlyPowerUsage(String khbh, String month) {
        BigDecimal monthPower = BigDecimal.ZERO;
        // 解析 yyyy-MM 格式为 LocalDate
        YearMonth yearMonth = YearMonth.parse(month, DateTimeFormatter.ofPattern("yyyy-MM"));
        LocalDate localDate = yearMonth.atDay(1);  // 设置为当月第一天
        Date date = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());

        if (isCurrentMonth(date)) {
            List<BillingVO> allResults = selectusergl(khbh);
            for (BillingVO vo : allResults) {
                // 累加 e
                if (vo.getZzdl() != null) {
                    monthPower = monthPower.add(vo.getE());
                }
            }
            return monthPower;
        }
        List<KhbhDbbh> khbhList = wxMapper.selectQldbzymx11(date, khbh);
        List<BillingVO> allResults = new ArrayList<>();

        for (KhbhDbbh kd : khbhList) {
            List<BillingVO> result = Ccompute1(date, kd);
            allResults.addAll(result);
        }
        for (BillingVO vo : allResults) {
            // 累加 e
            if (vo.getZzdl() != null) {
                monthPower = monthPower.add(vo.getE());
            }
        }
        return monthPower;
    }

    @Override
    public List<YearVO> yearlyPowerUsage(String khbh, String year) {
        Integer year1 = Integer.parseInt(year);
        List<YearVO> y1 = wxMapper.selectYear(khbh, year1);

        return y1.stream()
                .collect(Collectors.groupingBy(
                        vo -> String.format("%04d-%02d", vo.getNf(), vo.getYf()), // key: "yyyy-MM"
                        Collectors.mapping(Function.identity(), Collectors.toList())
                ))
                .entrySet().stream()
                .map(entry -> {
                    String[] parts = entry.getKey().split("-");
                    YearVO merged = new YearVO();

                    merged.setNf(Integer.parseInt(parts[0]));
                    merged.setYf(Integer.parseInt(parts[1]));
                    merged.setDate(entry.getKey());

                    // 累加所有同月份的 dbjs
                    BigDecimal totalDbjs = entry.getValue().stream()
                            .map(YearVO::getDbjs)
                            .filter(Objects::nonNull)
                            .reduce(BigDecimal.ZERO, BigDecimal::add);

                    merged.setDbjs(totalDbjs);

                    return merged;
                })
                .collect(Collectors.toList());
    }

    @Override
    public List<YearVO> monthlyPowerUsage1(String khbh, String month) {
        Date date = DateUtils.getFirstDayOfMonth(month);
        List<KhbhDbbh> khbhList = wxMapper.selectQldbzymx11(date, khbh);
        System.out.println(khbhList);
        Map<String, BigDecimal> mergedMap = new LinkedHashMap<>();
        List<YearVO> allResults = new ArrayList<>();
        for (KhbhDbbh kd : khbhList) {
            String dbbh = kd.getDbbh();
            List<YearVO> dailyPowers = calculateDailyPower(dbbh, month);

            // 合并到全局 map 中
            for (YearVO vo : dailyPowers) {
                String dateStr = vo.getDate().toString();
                mergedMap.merge(dateStr, vo.getDbjs(), BigDecimal::add);
            }
        }
        List<YearVO> result = new ArrayList<>();
        for (Map.Entry<String, BigDecimal> entry : mergedMap.entrySet()) {
            YearVO vo = new YearVO();
            vo.setDate(entry.getKey());
            vo.setDbjs(entry.getValue());
            result.add(vo);
        }
        return result;
    }

    @Override
    public List<DbkhhsjbVO> selectDbkhhsjb(String khbh) {
        return wxMapper.selectDbkhhsjb(khbh);
    }

    @Override
    public List<Qldbykhmxa> payment(String khbh) {
        return wxMapper.payment(khbh);
    }

    @Override
    public Qldbyczmx paymentRecord(String khbh) {
        return wxMapper.paymentRecord(khbh);
    }

    @Override
    public Dbysdbb postpaid(String khbh, String month) {
        Date date = DateUtils.getFirstDayOfMonth(month);
        return wxMapper.postpaid(khbh, date);
    }

    @Override
    public Dbysdbb prepaid(String khbh, String month) {
        Date date = DateUtils.getFirstDayOfMonth(month);
        return wxMapper.prepaid(khbh, date);
    }

    @Override
    public DbkhhsjbVO invoice(String khbh) {
        DbkhhsjbVO dbkhhsjbVO = wxMapper.invoice(khbh);
        return dbkhhsjbVO;
    }

    @Override
    public List<QldbysjmxVO> invoiceShow(String khbh, Integer year) {
        List<QldbysjmxVO> qldbysjmxVOS = wxMapper.invoiceShow(khbh, year);
        return qldbysjmxVOS;
    }

    @Override
    public Qldbykp selectInvoiceRecord(String khbh) {
        Qldbykp qldbykp = wxMapper.selectInvoiceRecord(khbh);
        return qldbykp;
    }

    @Override
    public Boolean payment1(String hkid, BigDecimal zhkje, String khbh, String zjly, String tname, Date sjrq, String remark) throws Exception {
        log.info("缴费后数据处理");

        // 定义一个集合存储所有新增记录的ID
        List<Integer> insertedIds = new ArrayList<>();
        // 按逗号分割
        String[] numberStrArray = hkid.split(",");

        // 转换为整数数组
        int[] numbers = new int[numberStrArray.length];
        for (int i = 0; i < numberStrArray.length; i++) {
            // 去除可能的空格并转换为整数
            numbers[i] = Integer.parseInt(numberStrArray[i].trim());
        }
        List<Qldbykhmx> qldbykhmx = billingMapper.payment(numbers);
        if (qldbykhmx == null || qldbykhmx.isEmpty()) {
            return false;
        }
        for (Qldbykhmx qdsx : qldbykhmx) {
            //全部收款
            if (zhkje.compareTo(qdsx.getYs()) >= 0) {
                QldbysjmxVO f1 = new QldbysjmxVO();
                f1.setZt(qdsx.getZt());
                f1.setQymc(qdsx.getQymc());
                f1.setKhbh(qdsx.getKhbh());
                f1.setHkid(qdsx.getHkid());
                f1.setNf(qdsx.getNf());
                f1.setYf(qdsx.getYf());
                f1.setHklx(qdsx.getHklx());
                f1.setHkrq(qdsx.getHkrq());
                f1.setHkks(qdsx.getHkks());
                f1.setHkjs(qdsx.getHkjs());
                f1.setHkzt("已收款");
                f1.setJflx(1);
                f1.setHkje(qdsx.getYs());
                f1.setYsje(qdsx.getYs());
                f1.setWsje(BigDecimal.ZERO);
                f1.setZnysje(qdsx.getZnj());
                f1.setSjrq(sjrq);
                f1.setTname(tname);
                f1.setTimestamp(new Date());
                f1.setZjly("缴费");
                f1.setZjbs(1);
                f1.setRemark(remark);
                //新增已收明细表记录qldbysjmx
                Boolean a = billingMapper.insertQldbysjmx(f1);
                if (!a) {
                    return false;
                }
                // 插入成功后，通过对象获取自动生成的ID并添加到集合中
                insertedIds.add(f1.getHkmxid());  // 假设主键字段是id，类型是Long

                Qldbykhmx q1 = new Qldbykhmx();
                q1.setHkid(qdsx.getHkid());
                q1.setHkzt("已收款");
                q1.setYsje(qdsx.getYs());
                q1.setWsje(BigDecimal.ZERO);
                q1.setSjrq(sjrq);
                //更新应收表qldbykhmx
                Boolean b = billingMapper.updateQldbykhmx(q1);
                zhkje = zhkje.subtract(qdsx.getYs());
                String sj = wxMapper.getSj(qdsx.getKhbh());
                if (StringUtils.isNotBlank(sj)) {
                    String templateParam = String.format(
                            "{\"nf\":\"%s\",\"yf\":\"%s\",\"je\":\"%s\"}",
                            qdsx.getNf(), qdsx.getYf(), qdsx.getYs()
                    );
                    Config config = new Config()
                            // 替换为你的 AccessKey ID
                            .setAccessKeyId("LTAI5tREYeNL71j7RfygWnHk")
                            // 替换为你的 AccessKey Secret
                            .setAccessKeySecret("rlNi5pJPYQVdo7cT7kzn7k0UeMmSNK");
                    // 阿里云短信服务的 endpoint
                    config.endpoint = "dysmsapi.aliyuncs.com";
                    Client client = new Client(config);
                    System.out.println("1111111111111111111111111111111111111111111111111111111111111" + sj);
                    SendSmsRequest sendSmsRequest = new SendSmsRequest()
                            .setPhoneNumbers(sj)
                            .setSignName("苏州青澜实业")  // 注意：这里的签名名称必须是在阿里云控制台已审核通过的
                            .setTemplateCode("SMS_493790207")
                            .setTemplateParam(templateParam);
                    // 获取响应对象
                    SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);
                    // 响应包含服务端响应的 body 和 headers
                    System.out.println(com.aliyun.teautil.Common.toJSONString(sendSmsResponse));
                }
                System.out.println("【青澜实业】尊敬的客户：您好！" + qdsx.getNf() + "年" + qdsx.getYf() + "月电费" + qdsx.getYs() + "元已核销。感谢您的支持！");
                if (!b) {
                    return false;
                }
                continue;
            }
            //部分收款
            if (zhkje.compareTo(qdsx.getYs()) < 0 && zhkje.compareTo(BigDecimal.ZERO) > 0) {
                QldbysjmxVO f1 = new QldbysjmxVO();
                f1.setZt(qdsx.getZt());
                f1.setQymc(qdsx.getQymc());
                f1.setKhbh(qdsx.getKhbh());
                f1.setHkid(qdsx.getHkid());
                f1.setNf(qdsx.getNf());
                f1.setYf(qdsx.getYf());
                f1.setHklx(qdsx.getHklx());
                f1.setHkrq(qdsx.getHkrq());
                f1.setHkks(qdsx.getHkks());
                f1.setHkjs(qdsx.getHkjs());
                f1.setHkzt("已收款");
                f1.setJflx(1);
                f1.setHkje(qdsx.getYs());
                f1.setYsje(zhkje);
                f1.setWsje(qdsx.getYs().subtract(zhkje));
                f1.setZnysje(qdsx.getZnj());
                f1.setSjrq(sjrq);
                f1.setTname(tname);
                f1.setTimestamp(new Date());
                f1.setZjly("缴费");
                f1.setZjbs(1);
                f1.setRemark(remark);
                //新增已收明细表记录qldbysjmx
                Boolean a = billingMapper.insertQldbysjmx(f1);
                if (!a) {
                    return false;
                }
                // 插入成功后，通过对象获取自动生成的ID并添加到集合中
                insertedIds.add(f1.getHkmxid());  // 假设主键字段是id，类型是Long

                Qldbykhmx q1 = new Qldbykhmx();
                q1.setHkid(qdsx.getHkid());
                q1.setHkzt("部分收款");
                q1.setYsje(qdsx.getYsje().add(zhkje));
                q1.setWsje(qdsx.getYs().subtract(zhkje));
                q1.setSjrq(sjrq);
                //更新应收表qldbykhmx
                Boolean b = billingMapper.updateQldbykhmx(q1);
                String sj = wxMapper.getSj(qdsx.getKhbh());
                if (StringUtils.isNotBlank(sj)) {
                    String templateParam = String.format(
                            "{\"nf\":\"%s\",\"yf\":\"%s\",\"je\":\"%s\",\"syje\":\"%s\"}",
                            qdsx.getNf(), qdsx.getYf(), zhkje, qdsx.getYs().subtract(zhkje)
                    );
                    Config config = new Config()
                            // 替换为你的 AccessKey ID
                            .setAccessKeyId("LTAI5tREYeNL71j7RfygWnHk")
                            // 替换为你的 AccessKey Secret
                            .setAccessKeySecret("rlNi5pJPYQVdo7cT7kzn7k0UeMmSNK");
                    // 阿里云短信服务的 endpoint
                    config.endpoint = "dysmsapi.aliyuncs.com";
                    Client client = new Client(config);
                    SendSmsRequest sendSmsRequest = new SendSmsRequest()
                            .setPhoneNumbers(sj)
                            .setSignName("苏州青澜实业")  // 注意：这里的签名名称必须是在阿里云控制台已审核通过的
                            .setTemplateCode("SMS_493725230")
                            .setTemplateParam(templateParam);
                    // 获取响应对象
                    SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);
                    // 响应包含服务端响应的 body 和 headers
                    System.out.println(com.aliyun.teautil.Common.toJSONString(sendSmsResponse));
                }

                System.out.println("【青澜实业】尊敬的客户：您好！" + qdsx.getNf() + "年" + qdsx.getYf() + "月电费已核销" + zhkje + "元，剩余" + qdsx.getYs().subtract(zhkje) + "元待缴纳，请你及时缴费");
                zhkje = zhkje.subtract(qdsx.getYs());
                if (!b) {
                    return false;
                }
            }
        }
        BigDecimal wfksjec = wxMapper.selectWfksjec1(khbh);
        if (wfksjec.compareTo(BigDecimal.ZERO) == 0) {
            QldbqyinfoPO qldbqyinfoPO = new QldbqyinfoPO();
            qldbqyinfoPO.setKhbh(khbh);
            qldbqyinfoPO.setQftx(0);
            qldbqyinfoPO.setQftxrq(null);
            Boolean b = wxMapper.updateQldbqyinfo(qldbqyinfoPO);
            if (!b) {
                return false;
            }
        }

        return true;
    }

    @Override
    public Boolean recharge(String khbh, BigDecimal recharge, String tname, String fylx) {
        log.info("充值数据处理");
//        if (fylx.equals("电费")){
//            //查询充值用户未付费账单
//            List<Qldbykhmx> qldbykhmxs = wxMapper.prepaidRecharge(khbh);
//            if (qldbykhmxs==null || qldbykhmxs.isEmpty()){return  true;}//没有待处理账单
//            for(Qldbykhmx qldbykhmx : qldbykhmxs){
//                //查询账户余额
//                BigDecimal  csyje = billingMapper.getcsyje(qldbykhmx.getKhbh());
//                if (csyje.compareTo(qldbykhmx.getZje()) >= 0){// 当余额大于等于当月应交电费时执行的逻辑
//                    QldbysjmxVO f1 = new QldbysjmxVO();
//                    f1.setZt(qldbykhmx.getZt());
//                    f1.setQymc(qldbykhmx.getQymc());
//                    f1.setKhbh(qldbykhmx.getKhbh());
//                    f1.setHkid(qldbykhmx.getHkid());
//                    f1.setNf(qldbykhmx.getNf());
//                    f1.setYf(qldbykhmx.getYf());
//                    f1.setHklx(qldbykhmx.getHklx());
//                    f1.setHkrq(qldbykhmx.getHkrq());
//                    f1.setHkks(qldbykhmx.getHkks());
//                    f1.setHkjs(qldbykhmx.getHkjs());
//                    f1.setHkzt("已收款");
//                    f1.setHkje(qldbykhmx.getYs());
//                    f1.setYsje(qldbykhmx.getYs());
//                    f1.setWsje(BigDecimal.ZERO);
//                    f1.setZnysje(qldbykhmx.getZnj());
//                    f1.setSjrq(new Date());
//                    f1.setTname(tname);
//                    f1.setTimestamp(new Date());
//                    f1.setZjly("充值");
//                    f1.setZjbs(1);
//                    f1.setJflx(2);
//                    //新增已收明细表记录qldbysjmx
//                    Boolean a = billingMapper.insertQldbysjmx(f1);
//                    if (!a){
//                        throw new RuntimeException("新增已收明细表记录失败");
//                    }
//                    Qldbykhmx q1=new Qldbykhmx();
//                    q1.setHkid(qldbykhmx.getHkid());
//                    q1.setHkzt("已收款");
//                    //已交电费
//                    q1.setYsje(qldbykhmx.getYs());
//                    //未交电费
//                    q1.setWsje(BigDecimal.ZERO);
//                    q1.setSjrq(new Date());
//                    //更新应收表qldbykhmx
//                    Boolean b = billingMapper.updateQldbykhmx(q1);
//                    if (!b){
//                        throw new RuntimeException("更新应收表qldbykhmx失败");
//                    }
//                    //通知客户：上月电表电费/容量费，当前剩余可用余额
//                }
//                if (csyje.compareTo(qldbykhmx.getZje()) < 0 && csyje.compareTo(BigDecimal.ZERO) != 0){// 当余额小于当月应交电费时并且不等于0执行的逻辑
//                    QldbysjmxVO f1 = new QldbysjmxVO();
//                    f1.setZt(qldbykhmx.getZt());
//                    f1.setQymc(qldbykhmx.getQymc());
//                    f1.setKhbh(qldbykhmx.getKhbh());
//                    f1.setHkid(qldbykhmx.getHkid());
//                    f1.setNf(qldbykhmx.getNf());
//                    f1.setYf(qldbykhmx.getYf());
//                    f1.setHklx(qldbykhmx.getHklx());
//                    f1.setHkrq(qldbykhmx.getHkrq());
//                    f1.setHkks(qldbykhmx.getHkks());
//                    f1.setHkjs(qldbykhmx.getHkjs());
//                    f1.setHkzt("已收款");
//
//                    //当余额少于应收电费时
//                    if (csyje.compareTo(qldbykhmx.getYs()) <= 0){
//                        f1.setHkje(qldbykhmx.getYs());
//                        f1.setYsje(csyje);//余额大于应收，应交电费就等于已收，处理滞纳金
//                        BigDecimal wsje = qldbykhmx.getYs().subtract(csyje);//未交电费计算
//                        f1.setWsje(wsje);//未交电费
//                        f1.setZnysje(BigDecimal.ZERO);
//                        f1.setSjrq(new Date());
//                        f1.setTname(tname);
//                        f1.setTimestamp(new Date());
//                        f1.setZjly("充值");
//                        f1.setZjbs(1);
//                        f1.setJflx(2);
//                        //新增已收明细表记录qldbysjmx
//                        Boolean a = billingMapper.insertQldbysjmx(f1);
//                        if (!a){
//                            throw new RuntimeException("新增已收明细表记录失败");
//                        }
//                        Qldbykhmx q1=new Qldbykhmx();
//                        q1.setHkid(qldbykhmx.getHkid());
//                        q1.setHkzt("部分收款");
//                        //已交电费
//                        q1.setYsje(csyje);
//                        //未交电费
//                        q1.setWsje(wsje);
//                        q1.setSjrq(new Date());
//                        //更新应收表qldbykhmx
//                        Boolean b = billingMapper.updateQldbykhmx(q1);
//                        if (!b){
//                            throw new RuntimeException("更新应收表qldbykhmx失败");
//                        }
//
//                    }else{//当余额大于应收电费时，多出来的余额就是已交滞纳金
//
//                        f1.setHkje(qldbykhmx.getYs());
//                        f1.setYsje(qldbykhmx.getYs());
//                        f1.setWsje(BigDecimal.ZERO);
//                        BigDecimal znj = csyje.subtract(qldbykhmx.getYs());
//                        f1.setZnysje(znj);//剩余可用余额为滞纳金
//                        f1.setSjrq(new Date());
//                        f1.setTname(tname);
//                        f1.setTimestamp(new Date());
//                        f1.setZjly("充值");
//                        f1.setZjbs(1);
//                        f1.setJflx(2);
//                        //新增已收明细表记录qldbysjmx
//                        Boolean a = billingMapper.insertQldbysjmx(f1);
//                        if (!a){
//                            throw new RuntimeException("新增已收明细表记录失败");
//                        }
//                        Qldbykhmx q1=new Qldbykhmx();
//                        q1.setHkid(qldbykhmx.getHkid());
//                        q1.setHkzt("部分收款");
//                        //已交电费
//                        q1.setYsje(qldbykhmx.getYs());
//                        //未交电费
//                        q1.setWsje(BigDecimal.ZERO);
//                        q1.setSjrq(new Date());
//                        //更新应收表qldbykhmx
//                        Boolean b = billingMapper.updateQldbykhmx(q1);
//                        if (!b){
//                            throw new RuntimeException("更新应收表qldbykhmx失败");
//                        }
//                    }
//                    //通知客户：上月电表电费/容量费，当前欠费
//                }
//                if (csyje.compareTo(BigDecimal.ZERO) == 0){
//                    log.info("账户余额为0,无法抵扣应收");
//                    break;
//                }
//            }
//
//        }

        if (fylx.equals("空调费")) {
            //查询充值用户未付费空调账单
            List<Qldbykhmx> qldbykhmxs = wxMapper.prepaidRechargekt(khbh);
            if (qldbykhmxs == null || qldbykhmxs.isEmpty()) {
                return true;
            }//没有待处理账单
            for (Qldbykhmx qldbykhmx : qldbykhmxs) {
                BigDecimal kcyje = wxMapper.selectKcyje(khbh);
                if (kcyje.compareTo(qldbykhmx.getZje()) >= 0) {// 当余额大于等于当月应交电费时执行的逻辑
                    QldbysjmxVO f1 = new QldbysjmxVO();
                    f1.setZt(qldbykhmx.getZt());
                    f1.setQymc(qldbykhmx.getQymc());
                    f1.setKhbh(qldbykhmx.getKhbh());
                    f1.setHkid(qldbykhmx.getHkid());
                    f1.setNf(qldbykhmx.getNf());
                    f1.setYf(qldbykhmx.getYf());
                    f1.setHklx(qldbykhmx.getHklx());
                    f1.setHkrq(qldbykhmx.getHkrq());
                    f1.setHkks(qldbykhmx.getHkks());
                    f1.setHkjs(qldbykhmx.getHkjs());
                    f1.setHkzt("已收款");
                    f1.setHkje(qldbykhmx.getYs());
                    f1.setYsje(qldbykhmx.getYs());
                    f1.setWsje(BigDecimal.ZERO);
                    f1.setZnysje(qldbykhmx.getZnj());
                    f1.setSjrq(new Date());
                    f1.setTname(tname);
                    f1.setTimestamp(new Date());
                    f1.setZjly("充值");
                    f1.setZjbs(1);
                    f1.setJflx(2);
                    //新增已收明细表记录qldbysjmx
                    Boolean a = billingMapper.insertQldbysjmx(f1);
                    if (!a) {
                        throw new RuntimeException("新增已收明细表记录失败");
                    }
                    Qldbykhmx q1 = new Qldbykhmx();
                    q1.setHkid(qldbykhmx.getHkid());
                    q1.setHkzt("已收款");
                    //已交电费
                    q1.setYsje(qldbykhmx.getYs());
                    //未交电费
                    q1.setWsje(BigDecimal.ZERO);
                    q1.setSjrq(new Date());
                    //更新应收表qldbykhmx
                    Boolean b = billingMapper.updateQldbykhmx(q1);
                    if (!b) {
                        throw new RuntimeException("更新应收表qldbykhmx失败");
                    }
                    //通知客户：上月电表电费/容量费，当前剩余可用余额
                }
                if (kcyje.compareTo(qldbykhmx.getZje()) < 0 && kcyje.compareTo(BigDecimal.ZERO) != 0) {// 当余额小于当月应交电费时并且不等于0执行的逻辑
                    QldbysjmxVO f1 = new QldbysjmxVO();
                    f1.setZt(qldbykhmx.getZt());
                    f1.setQymc(qldbykhmx.getQymc());
                    f1.setKhbh(qldbykhmx.getKhbh());
                    f1.setHkid(qldbykhmx.getHkid());
                    f1.setNf(qldbykhmx.getNf());
                    f1.setYf(qldbykhmx.getYf());
                    f1.setHklx(qldbykhmx.getHklx());
                    f1.setHkrq(qldbykhmx.getHkrq());
                    f1.setHkks(qldbykhmx.getHkks());
                    f1.setHkjs(qldbykhmx.getHkjs());
                    f1.setHkzt("已收款");
                    //当余额少于应收电费时
                    if (kcyje.compareTo(qldbykhmx.getYs()) <= 0) {
                        f1.setHkje(qldbykhmx.getYs());
                        f1.setYsje(kcyje);//余额大于应收，应交电费就等于已收，处理滞纳金
                        BigDecimal wsje = qldbykhmx.getYs().subtract(kcyje);//未交电费计算
                        f1.setWsje(wsje);//未交电费
                        f1.setZnysje(BigDecimal.ZERO);
                        f1.setSjrq(new Date());
                        f1.setTname(tname);
                        f1.setTimestamp(new Date());
                        f1.setZjly("充值");
                        f1.setZjbs(1);
                        f1.setJflx(2);
                        //新增已收明细表记录qldbysjmx
                        Boolean a = billingMapper.insertQldbysjmx(f1);
                        if (!a) {
                            throw new RuntimeException("新增已收明细表记录失败");
                        }
                        Qldbykhmx q1 = new Qldbykhmx();
                        q1.setHkid(qldbykhmx.getHkid());
                        q1.setHkzt("部分收款");
                        //已交电费
                        q1.setYsje(kcyje);
                        //未交电费
                        q1.setWsje(wsje);
                        q1.setSjrq(new Date());
                        //更新应收表qldbykhmx
                        Boolean b = billingMapper.updateQldbykhmx(q1);
                        if (!b) {
                            throw new RuntimeException("更新应收表qldbykhmx失败");
                        }

                    } else {//当余额大于应收电费时，多出来的余额就是已交滞纳金

                        f1.setHkje(qldbykhmx.getYs());
                        f1.setYsje(qldbykhmx.getYs());
                        f1.setWsje(BigDecimal.ZERO);
                        BigDecimal znj = kcyje.subtract(qldbykhmx.getYs());
                        f1.setZnysje(znj);//剩余可用余额为滞纳金
                        f1.setSjrq(new Date());
                        f1.setTname(tname);
                        f1.setTimestamp(new Date());
                        f1.setZjly("充值");
                        f1.setZjbs(1);
                        f1.setJflx(2);
                        //新增已收明细表记录qldbysjmx
                        Boolean a = billingMapper.insertQldbysjmx(f1);
                        if (!a) {
                            throw new RuntimeException("新增已收明细表记录失败");
                        }
                        Qldbykhmx q1 = new Qldbykhmx();
                        q1.setHkid(qldbykhmx.getHkid());
                        q1.setHkzt("部分收款");
                        //已交电费
                        q1.setYsje(qldbykhmx.getYs());
                        //未交电费
                        q1.setWsje(BigDecimal.ZERO);
                        q1.setSjrq(new Date());
                        //更新应收表qldbykhmx
                        Boolean b = billingMapper.updateQldbykhmx(q1);
                        if (!b) {
                            throw new RuntimeException("更新应收表qldbykhmx失败");
                        }
                    }
                    //通知客户：上月电表电费/容量费，当前欠费
                }
                if (kcyje.compareTo(BigDecimal.ZERO) == 0) {
                    log.info("账户余额为0,无法抵扣应收");
                    break;
                }
            }
        }
        return true;
    }

    @Override
    public List<Qldbyczmx> paymentRecord2(String khbh, String zt, Integer jflx, String fylx, String month, String qymc) {
        if (month != null) {
            Date date = DateUtils.getFirstDayOfMonth(month);
            List<Qldbyczmx> qldbyczmx = billingMapper.paymentRecord2(khbh, zt, jflx, fylx, date, qymc);
            return qldbyczmx;
        }
        Date date = null;
        List<Qldbyczmx> qldbyczmx = billingMapper.paymentRecord2(khbh, zt, jflx, fylx, date, qymc);
        return qldbyczmx;
    }

    @Override
    public List<RechargeRecord> tenantysmx(String khbh, String zt) {
        List<RechargeRecord> rechargeRecords = wxMapper.tenantysmx1(khbh, zt);
        for (RechargeRecord rechargeRecord : rechargeRecords) {
            Date date = DateUtils.getFirstDayOfMonth(rechargeRecord.getMonth());
            List<QldbysjmxVO> qldbyczmxList = wxMapper.tenantysmx11(khbh, zt, date);
            rechargeRecord.setQldbyczmxList(qldbyczmxList);
        }
        return rechargeRecords;
    }

    @Override
    public List<Qldbykhmx> postpaid1(String khbh, String zt, Integer status) {
        Date date = new Date();
        List<Qldbykhmx> qldbykhmxList = wxMapper.postpaid1(khbh, zt, status, date);
        return qldbykhmxList;
    }

    @Override
    public List<DbkhhsjbVO> postpaidShow(String qymc, String bm, Integer dbqx) {
        if (dbqx == 8) {
            String zt = null;
            List<DbkhhsjbVO> qldbykhmxList = wxMapper.postpaidShow(qymc, zt);
            return qldbykhmxList;
        }
        List<DbkhhsjbVO> qldbykhmxList = wxMapper.postpaidShow(qymc, bm);
        return qldbykhmxList;
    }

    @Override
    public List<Qldbyczmx> paymentRecord111(String khbh, String zt, Integer jflx, String month, String qymc) {
        Date date = DateUtils.getFirstDayOfMonth(month);
        List<Qldbyczmx> qldbykhmxList = wxMapper.paymentRecord111(khbh, zt, jflx, date, qymc);
        return qldbykhmxList;
    }

    @Override
    public List<QldbysjmxVO> wxmonth(String qymc, String zt, Date date, Integer dbqx) {
        if (dbqx == 3) {
            List<QldbysjmxVO> qldbykhmxList = wxMapper.wxmonth(qymc, zt, date, dbqx);
            return qldbykhmxList;
        }
        if (dbqx == 8) {
            String zt1 = null;
            List<QldbysjmxVO> qldbykhmxList = wxMapper.wxmonth(qymc, zt1, date, dbqx);
            return qldbykhmxList;
        }
        return Collections.emptyList();
    }

    public List<YearVO> calculateDailyPower(String dbbh, String month) {
        List<YearVO> dailyReads = wxMapper.selectDailyReadsByDbbhAndMonth(dbbh, month);

        Map<String, BigDecimal> dateToSum = new LinkedHashMap<>();

        for (YearVO vo : dailyReads) {
            String dateKey = vo.getDate().split(" ")[0];
            BigDecimal dbjs = vo.getDbjs();

            dateToSum.put(dateKey, dateToSum.getOrDefault(dateKey, BigDecimal.ZERO).add(dbjs));
        }

        List<YearVO> result = new ArrayList<>();
        result = dateToSum.entrySet().stream()
                .map(entry -> new YearVO().setDate(entry.getKey()).setDbjs(entry.getValue()))
                .collect(Collectors.toList());

        return result;
    }

    public List<BillingVO> CcomputeLastYear(KhbhDbbh kd, LocalDate inputDate) {
        List<QldbzymxPO> poList = billingMapper.selectQldbzymx(kd);
        List<BillingVO> result = new ArrayList<>();
        for (QldbzymxPO po : poList) {
            result.add(processBillingLastYear(po, inputDate));
        }
        return result;
    }

    //工具类通过khbh查询所有电表数据
    public BillingVO processBillingLastYear(QldbzymxPO po, LocalDate inputDate) {
        // 处理入住时间匹配当年的情况
        LocalDate poDate = convertToLocalDate(po.getQysj());//启用时间
        LocalDate poDate1 = convertToLocalDate(po.getTysj());//退佣时间
        Date date = Date.from(inputDate.atStartOfDay(ZoneId.systemDefault()).toInstant());//将inputDate转换为Date
        if (isSameYear(poDate, inputDate) && poDate1 == null) {
            System.out.println("处理入住时间匹配当年的情况");
            BigDecimal c = po.getCsdl();
            //
            MouthReadPO po1 = wxMapper.selectLastYearRead(po.getDbbh(), date);
            BigDecimal b = po1.getYearRead();
            Date t1 = po.getQysj();
            Date t2 = po1.getTimestamp();
            BigDecimal zzdl = b.subtract(c);
            BigDecimal a = zzdl.multiply(po.getDbbl());
            log.info("当月结算（入住）：" + zzdl);
            return createBillingVO(po, zzdl, b, c, t1, t2);
        }

        // 处理退租时间匹配年的情况
        if (isSameYear(poDate1, inputDate) && notSameYear(poDate, inputDate)) {
            System.out.println("处理退租时间匹配年的情况");
            BigDecimal b = po.getZzdl();
            //获取单电表年度数据
            MouthReadPO po1 = wxMapper.selectLastYearRead1(po.getDbbh(), date);
            BigDecimal c = po1.getYearRead();
            Date t1 = po1.getTimestamp();
            Date t2 = po.getTysj();
            BigDecimal zzdl = b.subtract(c);
            BigDecimal a = zzdl.multiply(po.getDbbl());
            log.info("当月结算（退宿）：" + a);
            return createBillingVO(po, zzdl, b, c, t1, t2);
        }

        // 可选：同时满足入住和退宿都在当年的情况处理
        if (isSameYear(poDate, inputDate) && isSameYear(poDate1, inputDate)) {

            System.out.println("同时满足入住和退宿都在当年的情况处理");
            // 特殊情况处理逻辑可在此添加
            BigDecimal c = po.getCsdl();
            BigDecimal b = po.getZzdl();
            Date t1 = po.getQysj();
            Date t2 = po.getTysj();
            BigDecimal zzdl = b.subtract(c);
            BigDecimal a = zzdl.multiply(po.getDbbl());
            log.info("当月结算（入住+退宿）：" + a);
            return createBillingVO(po, zzdl, b, c, t1, t2);
        }
        System.out.println("获取单电表年度数据");

        //获取单电表年度数据
        //前一年数据
        MouthReadPO po1 = wxMapper.selectLastYearRead1(po.getDbbh(), date);
        //这一年的数据
        MouthReadPO po2 = wxMapper.selectLastYearRead(po.getDbbh(), date);
        BigDecimal c = po2.getMouthRead();
        Date t1 = po1.getTimestamp();
        Date t2 = po2.getTimestamp();
        BigDecimal b = po1.getYearRead();
        BigDecimal zzdl = c.subtract(b);
        BigDecimal a = zzdl.multiply(po.getDbbl());
        log.info("当月结算（入住+退宿）：" + a);
        return createBillingVO(po, zzdl, b, c, t1, t2);
    }

    //工具类通过khbh查询所有电表数据
    public List<BillingVO> CcomputeYear(KhbhDbbh kd, LocalDate inputDate) {
        List<QldbzymxPO> poList = billingMapper.selectQldbzymx(kd);
        List<BillingVO> result = new ArrayList<>();
        for (QldbzymxPO po : poList) {
            result.add(processBillingYear(po, inputDate));
        }
        return result;
    }

    public boolean isCurrentMonth(Date date) {
        if (date == null) return false;

        LocalDate inputDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        LocalDate now = LocalDate.now();

        return inputDate.getYear() == now.getYear() &&
                inputDate.getMonth() == now.getMonth();
    }

    public List<BillingVO> Ccompute1(Date date, KhbhDbbh kd) {
        List<QldbzymxPO> poList = billingMapper.selectQldbzymx(kd);
        LocalDate now = convertToLocalDate(date);
        List<BillingVO> result = new ArrayList<>();
        for (QldbzymxPO po : poList) {
            result.add(processBilling1(po, now));
        }
        return result;
    }

    //工具类通过khbh查询所有电表数据
    public BillingVO processBillingYear(QldbzymxPO po, LocalDate inputDate) {
        // 处理入住时间匹配当月的情况
        LocalDate poDate = convertToLocalDate(po.getQysj());
        LocalDate poDate1 = convertToLocalDate(po.getTysj());
        if (isSameYear(poDate, inputDate) && poDate1 == null) {
            System.out.println("处理入住时间匹配当月的情况");
            BigDecimal c = po.getCsdl();
            //
            MouthReadPO po1 = wxMapper.selectDayRead(po.getDbbh());
            BigDecimal b = po1.getMouthRead();
            Date t1 = po.getQysj();
            Date t2 = po1.getTimestamp();
            BigDecimal zzdl = b.subtract(c);
            BigDecimal a = zzdl.multiply(po.getDbbl());
            log.info("当月结算（入住）：" + zzdl);
            return createBillingVO(po, zzdl, b, c, t1, t2);
        }

        // 处理退租时间匹配年的情况
        if (isSameYear(poDate1, inputDate) && notSameYear(poDate, inputDate)) {
            System.out.println("处理退租时间匹配年的情况");
            BigDecimal b = po.getZzdl();
            //获取单电表年度数据
            MouthReadPO po1 = billingMapper.selectYearRead(po.getDbbh());
            BigDecimal c = po1.getYearRead();
            Date t1 = po1.getTimestamp();
            Date t2 = po.getTysj();
            BigDecimal zzdl = b.subtract(c);
            BigDecimal a = zzdl.multiply(po.getDbbl());
            log.info("当月结算（退宿）：" + a);
            return createBillingVO(po, zzdl, b, c, t1, t2);
        }

        // 可选：同时满足入住和退宿都在当年的情况处理
        if (isSameYear(poDate, inputDate) && isSameYear(poDate1, inputDate)) {
            System.out.println("同时满足入住和退宿都在当年的情况处理");
            // 特殊情况处理逻辑可在此添加
            BigDecimal c = po.getCsdl();
            BigDecimal b = po.getZzdl();
            Date t1 = po.getQysj();
            Date t2 = po.getTysj();
            BigDecimal zzdl = b.subtract(c);
            BigDecimal a = zzdl.multiply(po.getDbbl());
            log.info("当月结算（入住+退宿）：" + a);
            return createBillingVO(po, zzdl, b, c, t1, t2);
        }
        System.out.println("获取单电表年度数据");
        //获取单电表年度数据
        //当年
        MouthReadPO po1 = billingMapper.selectYearRead(po.getDbbh());
        //当今
        MouthReadPO po2 = wxMapper.selectDayRead(po.getDbbh());
        BigDecimal c = po2.getMouthRead();
        Date t1 = po1.getTimestamp();
        Date t2 = po2.getTimestamp();
        BigDecimal b = po1.getYearRead();
        BigDecimal zzdl = c.subtract(b);
        BigDecimal a = zzdl.multiply(po.getDbbl());
        log.info("当月结算（入住+退宿）：" + a);
        return createBillingVO(po, zzdl, b, c, t1, t2);
    }

    public List<BillingVO> Ccompute(KhbhDbbh kd) {
        List<QldbzymxPO> poList = billingMapper.selectQldbzymx(kd);
        LocalDate now = LocalDate.now();
        List<BillingVO> result = new ArrayList<>();
        for (QldbzymxPO po : poList) {
            result.add(processBilling(po, now));
        }
        return result;
    }

    public BillingVO processBilling(QldbzymxPO po, LocalDate now) {
        // 处理入住时间匹配当月的情况
        LocalDate poDate = convertToLocalDate(po.getQysj());
        LocalDate poDate1 = convertToLocalDate(po.getTysj());
        if (isSameYearAndMonth(poDate, now) && poDate1 == null) {
            BigDecimal c = po.getCsdl();
            //
            MouthReadPO po1 = wxMapper.selectDayRead(po.getDbbh());
            Date t1 = null;
            Date t2 = null;
            BigDecimal b = BigDecimal.ZERO;
            BigDecimal zzdl = BigDecimal.ZERO;
            if (ObjectUtils.isNotEmpty(po1)) {
                b = po1.getMouthRead() == null ? BigDecimal.ZERO : po1.getMouthRead();
                t1 = po.getQysj();
                t2 = po1.getTimestamp();
                zzdl = b.subtract(c);
                BigDecimal a = zzdl.multiply(po.getDbbl());
                log.info("当月结算（入住）：" + zzdl);
            }
            return createBillingVO(po, zzdl, b, c, t1, t2);
        }

        // 处理退租时间匹配上个月的情况
        if (isSameYearAndMonth(poDate1, now) && notSameYearAndMonth(poDate, now)) {
            BigDecimal b = po.getZzdl();
            MouthReadPO po1 = billingMapper.selectMouthRead1(po.getDbbh());
            BigDecimal c = BigDecimal.ZERO;
            Date t1 = null;
            Date t2 = null;
            BigDecimal zzdl = BigDecimal.ZERO;
            if (ObjectUtils.isNotEmpty(po1)) {
                c = po1.getMouthRead() == null ? BigDecimal.ZERO : po1.getMouthRead();
                t1 = po1.getTimestamp();
                t2 = po.getTysj();
                zzdl = b.subtract(c);
                BigDecimal a = zzdl.multiply(po.getDbbl());
                log.info("当月结算（退宿）：" + a);
            }
            return createBillingVO(po, zzdl, b, c, t1, t2);
        }

        // 可选：同时满足入住和退宿都在上个月的情况处理
        if (isSameYearAndMonth(poDate, now) && isSameYearAndMonth(poDate1, now)) {
            // 特殊情况处理逻辑可在此添加
            BigDecimal c = po.getCsdl();
            BigDecimal b = po.getZzdl();
            Date t1 = po.getQysj();
            Date t2 = po.getTysj();
            BigDecimal zzdl = b.subtract(c);
            BigDecimal a = zzdl.multiply(po.getDbbl());
            log.info("当月结算（入住+退宿）：" + a);
            return createBillingVO(po, zzdl, b, c, t1, t2);
        }

        //当月
        MouthReadPO po1 = wxMapper.selectDayRead(po.getDbbh());
        //上月
        MouthReadPO po2 = wxMapper.selectMouthRead1(po.getDbbh());
        BigDecimal c = po2.getMouthRead();
        Date t1 = po1.getTimestamp();
        Date t2 = po2.getTimestamp();
        BigDecimal b = po1.getMouthRead();
        BigDecimal zzdl = b.subtract(c);
        BigDecimal a = zzdl.multiply(po.getDbbl());
        log.info("当月结算（入住+退宿）：" + a);
        return createBillingVO(po, zzdl, b, c, t1, t2);
    }

    // 工具方法：将 Date 转换为 LocalDate
    private LocalDate convertToLocalDate(Date date) {
        return date != null ? date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate() : null;
    }

    // 工具方法：比较年份与月份是否一致
    private boolean isSameYearAndMonth(LocalDate date1, LocalDate date2) {
        return date1 != null && date2 != null
                && date1.getYear() == date2.getYear()
                && date1.getMonth() == date2.getMonth();
    }

    private boolean notSameYearAndMonth(LocalDate date1, LocalDate date2) {
        return date1 != null && date2 != null
                && date1.getYear() != date2.getYear()
                && date1.getMonth() != date2.getMonth();
    }

    // 工具方法：比较年份是否一致
    private boolean isSameYear(LocalDate date1, LocalDate date2) {
        return date1 != null && date2 != null
                && date1.getYear() == date2.getYear();
    }

    private boolean notSameYear(LocalDate date1, LocalDate date2) {
        return date1 != null && date2 != null
                && date1.getYear() != date2.getYear();
    }

    // 构建返回对象
    private BillingVO createBillingVO(QldbzymxPO po, BigDecimal zzdl, BigDecimal b, BigDecimal c, Date t1, Date t2) {
        BillingVO billingVO = new BillingVO();
        //电表基础信息
        AmmeterResultVO ammeterResultVO = wxMapper.selectAmmeterx(po.getDbbh());
        billingVO.setLc(ammeterResultVO.getLc());
        billingVO.setLocation(ammeterResultVO.getLocation());
        billingVO.setDbyt(ammeterResultVO.getDbyt());
        billingVO.setDbzt(ammeterResultVO.getDbzt());
        billingVO.setZzdl(zzdl);
        billingVO.setQymc(po.getQymc());
        billingVO.setKhbh(po.getKhbh());
        billingVO.setZt(po.getZt());
        billingVO.setFjh(po.getFjh());
        billingVO.setDbbh(po.getDbbh());
        billingVO.setC(c);
        billingVO.setB(b);
        billingVO.setDbdj(po.getDfdj());
        billingVO.setMagnification(po.getDbbl());
        billingVO.setE(zzdl.multiply(po.getDbbl()));
        billingVO.setMount(zzdl.multiply(po.getDfdj()).multiply(po.getDbbl()));
        billingVO.setEnergyMeterIp(po.getEnergyMeterIp());
        return billingVO;
    }

    public BillingVO processBilling1(QldbzymxPO po, LocalDate now) {
        // 处理入住时间匹配上个月的情况
        LocalDate poDate = convertToLocalDate(po.getQysj());
        LocalDate poDate1 = convertToLocalDate(po.getTysj());
        if (isSameYearAndMonth(poDate, now) && poDate1 == null) {
            BigDecimal c = po.getCsdl();
            MouthReadPO po1 = billingMapper.selectMouthRead(po.getDbbh());
            BigDecimal b = po1.getMouthRead();
            Date t1 = po.getQysj();
            Date t2 = po1.getTimestamp();
            BigDecimal zzdl = b.subtract(c);
            BigDecimal a = zzdl.multiply(po.getDbbl());
            log.info("当月结算（入住）：" + zzdl);

            return createBillingVO(po, zzdl, b, c, t1, t2);
        }

        // 处理退租时间匹配上个月的情况
        if (isSameYearAndMonth(poDate1, now) && notSameYearAndMonth(poDate, now)) {
            BigDecimal b = po.getZzdl();
            MouthReadPO po1 = billingMapper.selectMouthRead1(po.getDbbh());
            BigDecimal c = po1.getMouthRead();
            Date t1 = po1.getTimestamp();
            Date t2 = po.getTysj();
            BigDecimal zzdl = b.subtract(c);
            BigDecimal a = zzdl.multiply(po.getDbbl());
            log.info("当月结算（退宿）：" + a);
            return createBillingVO(po, zzdl, b, c, t1, t2);
        }

        // 可选：同时满足入住和退宿都在上个月的情况处理
        if (isSameYearAndMonth(poDate, now) && isSameYearAndMonth(poDate1, now)) {
            // 特殊情况处理逻辑可在此添加
            BigDecimal c = po.getCsdl();
            BigDecimal b = po.getZzdl();
            Date t1 = po.getQysj();
            Date t2 = po.getTysj();
            BigDecimal zzdl = b.subtract(c);
            BigDecimal a = zzdl.multiply(po.getDbbl());
            log.info("当月结算（入住+退宿）：" + a);
            return createBillingVO(po, zzdl, b, c, t1, t2);
        }

        //当月
        MouthReadPO po1 = billingMapper.selectMouthRead(po.getDbbh());
        //上月
        MouthReadPO po2 = billingMapper.selectMouthRead1(po.getDbbh());
        BigDecimal c = po2.getMouthRead();
        Date t1 = po1.getTimestamp();
        Date t2 = po2.getTimestamp();
        BigDecimal b = po1.getMouthRead();
        BigDecimal zzdl = b.subtract(c);
        BigDecimal a = zzdl.multiply(po.getDbbl());
        log.info("当月结算（入住+退宿）：" + a);
        return createBillingVO(po, zzdl, b, c, t1, t2);
    }


    /**
     * 获取该客户名下所有电表实时电量累积总和
     *
     * @param khbh 客户编号
     * @return 电表实时电量累积总和
     */
    @Override
    public AmmeterResultPo selectAmmeterResult(String khbh) {
        try {
            // 查询该客户名下的所有电表
            List<KhbhDbbh> khbhList = wxMapper.selectQldbzymx11(null, khbh);
            if (CollectionUtils.isEmpty(khbhList)) {
                return null;
            }
            AmmeterResultPo result = new AmmeterResultPo();
            final BigDecimal[] totalPower = {BigDecimal.ZERO};
            /* 遍历所有电表总电量 */
            khbhList.forEach(khbhDbbh -> {
                AmmeterResultPo closestAmmeterData = ammeterService.getClosestAmmeterData(khbhDbbh.getDbbh());
                totalPower[0] = totalPower[0].add(closestAmmeterData.getTotalPower());
            });

            result.setTotalPower(totalPower[0]);
            return result;
        } catch (Exception e) {
            log.error("查询实时电量失败: {}", e.toString());
            return null;
        }
    }
}
